package ee.ut.cs.mc.madp.p2pdivider.task;

import static ee.ut.cs.mc.madp.p2pdivider.BaseDividerActivity.HANDLER_TOAST;
import static ee.ut.cs.mc.madp.p2pdivider.BaseDividerActivity.OP_SEPARATOR;
import static ee.ut.cs.mc.madp.p2pdivider.BaseDividerActivity.SERVERPORT;

import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;

import android.net.wifi.p2p.WifiP2pInfo;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import ee.ut.cs.mc.madp.p2pdivider.BaseDividerActivity;
import ee.ut.cs.mc.madp.p2pdivider.Command;
import ee.ut.cs.mc.madp.p2pdivider.networking.DividerClient;

/**
 * @author Kaarel Jõgeva
 *
 */
public class SendGreetingsTask extends AsyncTask<InetAddress, Void, InetAddress> {

    public static final String TAG = SendGreetingsTask.class.getCanonicalName();
    private final boolean isAppHost;
    private final Handler handler;
    private DividerClient client;
    private final WifiP2pInfo info;

    public SendGreetingsTask(Handler handler, WifiP2pInfo info, boolean isAppHost) {
        this.isAppHost = isAppHost;
        this.handler = handler;
        this.info = info;
    }

    @Override
    protected InetAddress doInBackground(InetAddress... params) {
        Log.i(TAG, "Sending greetings...");
        try {
            boolean connected = false;
            while (!connected) {
                client = new DividerClient(handler, new URI("ws://" + params[0].getHostAddress() + ":" + SERVERPORT)); // It is not reusable
                connected = client.connectBlocking();
            }
            client.send(Command.IP.name() + OP_SEPARATOR + Boolean.toString(isAppHost));

            /*
             * if (!isHost) { // If we have divider client, then hold the connection open
             * while (/* !isCancelled() &&
             *//*
             * client.getConnection() != null && !client.getConnection().isClosed() && client.getNewHost() == null) {
             * Thread.sleep(1000);
             * }
             * }
             */
            /* return client.getNewHost() == null && */

            return !info.isGroupOwner ? info.groupOwnerAddress : client.getConnection().getLocalSocketAddress().getAddress();
        } catch (URISyntaxException e) {
            Message.obtain(handler, HANDLER_TOAST, "URI is wrong! " + e.getLocalizedMessage()).sendToTarget();
            // } catch (InterruptedException e) {
            // Thread.currentThread().interrupt();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            client.close();
        }

        return null;
    }

    @Override
    protected void onPostExecute(InetAddress result) {
        Message.obtain(handler, BaseDividerActivity.HANDLER_START_CLIENT, result).sendToTarget();
    }
}